//
//  LBCategoryMainView.m
//  jslj
//
//  Created by luckyRoy on 2017/10/10.
//  Copyright © 2017年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBCategoryMainView.h"
#import "LBFacListView.h"
#import "LBCategoryManager.h"
#import "LBAlert.h"
#import "LBCategorySectionView.h"
#import "LBPopuViewCell.h"
#import <UIButton+LBStyle.h>
#import "LBCategoryTopHeaderReusableView.h"
#import "LBCategorySelectedChildView.h"
#import "LBNewCategorySearchView.h"
#import <Masonry.h>
#import <LBLoadingView.h>
#import <LBFacAllHeader.h>
#import <UIColor+LBColor.h>
#import "UIApplication+LBViewController.h"
#import "LBCategoryHeaderViewModel.h"
#import <LBToastView.h>
#import "LBCategorySearchViewController.h"
#import "LBCategorySettingModel.h"
#import "LBFacCategoryFlowLayout.h"
#import "LBCYThreeLevelShowViewController.h"
#import "UIButton+LBImageTitleStyle.h"
#import "LBCategorySelectedView.h"
#import "LBCategoryPopuView.h"
#import "UIView+LBEmptyData.h"

static NSInteger const LBCategoryMainViewPopuViewMaxLines = 3;

typedef enum : NSUInteger {
    LBCategoryMainViewDelTypeInTwoLevel,//在二级
    LBCategoryMainViewDelTypeInThreeLevel,//在三级
    LBCategoryMainViewDelTypeNoIn,//都不在
} LBCategoryMainViewDelMoveToType;

@interface LBCategoryMainView ()

@property (strong, nonatomic) LBFacListView *facCollectionView;

@property (nonatomic, copy) LBCategoryMainViewBlock choseBlock;

@property (nonatomic, weak) LBCategorySettingModel *settingModel;

@property (nonatomic, strong) NSMutableArray *showListArray;

@property (nonatomic, strong) LBCategoryMainViewLayout *viewLayout;

@property (nonatomic, assign) LBCategoryMainViewDelMoveToType moveToType;

//optional UI

@property (nonatomic, strong) LBNewCategorySearchView *searchView;

@property (nonatomic, strong) UIButton *confirmButton;

//@property (nonatomic, strong) UIButton *lookAllButton;
//
@property (nonatomic, strong) LBCategorySelectedView *bottomSelectedView;

@end

@implementation LBCategoryMainView

- (instancetype)initWithFrame:(CGRect)frame
                 settingModel:(LBCategorySettingModel *)settingModel
                   viewLayout:(LBCategoryMainViewLayout *)viewLayout
                     complete:(LBCategoryMainViewBlock)complete
{
    self = [super initWithFrame:frame];
    if (self) {
        self.settingModel = settingModel;
        self.choseBlock = complete;
        self.viewLayout = viewLayout;
        
        if (LBCategorySettingPageTypeHomePage == viewLayout.pageType) {
            self.settingModel.confirmBlock = complete;
        } else if (LBCategorySettingPageTypeThreeLevel == viewLayout.pageType) {
            LBCategoryModel *lastModel = [settingModel.currentShowArray lastObject];
            if (lastModel.parName) {
                self.searchView.searchBar.placeholder = [NSString stringWithFormat:@"搜索%@分类",lastModel.parName];
            }
        }

        [self createAllView];
    }
    return self;
}

- (void)createAllView
{
    [self addSubview:self.facCollectionView];
    
    [self updateViewLayout];
    __weak __typeof(&*self)weakSelf = self;
    
    if (LBCategorySettingPageTypeHomePage == self.viewLayout.pageType) {
        //仅主页接受变化
        [self.settingModel setHomePageChangeBlock:^{
            [weakSelf modelSelectedChange];
            weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:weakSelf.viewLayout.pageType];
            [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
        }];
    } else if (LBCategorySettingPageTypeThreeLevel == weakSelf.viewLayout.pageType) {
        //仅三级页面接受变化
        [self.settingModel setThreeLevelChangeBlock:^{
            weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:weakSelf.viewLayout.pageType];
            [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
            [weakSelf allModelSelectedChange];
        }];
    } else {
        [self.settingModel setSearchLevelChangeBlock:^{
            weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:weakSelf.viewLayout.pageType];
            [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
        }];
    }
}

- (void)updateViewLayout
{
    UIView *topView = nil;
    UIView *bottomView = nil;
    
    if (self.viewLayout.isShowSearchView) {

        [self addSubview:self.searchView];

        [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            make.height.mas_equalTo([LBNewCategorySearchView heightForView]);
        }];
        
        topView = self.searchView;
    }
    if (self.viewLayout.isShowConfirmView) {
        
        [self addSubview:self.confirmButton];
        
        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
            make.left.offset(0);
            make.right.offset(0);
            make.height.mas_equalTo(48);
        }];
        
        bottomView = self.confirmButton;
    }
    
    if (self.viewLayout.isShowBottomSelectedView) {
        
        [self addSubview:self.bottomSelectedView];
        
        bottomView = self.bottomSelectedView;

        [self updateSelectedView];
    }
    
//    if (self.viewLayout.isShowLookingAllView) {
//
//        [self addSubview:self.lookAllButton];
//
//        [self.lookAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.offset(0);
//            make.left.offset(0);
//            make.right.offset(0);
//            make.height.mas_equalTo(48);
//        }];
//
//        [self.lookAllButton lb_setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:0];
//        
//        bottomView = self.lookAllButton;
//    }
    
    [self.facCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (topView) {
            make.top.mas_equalTo(topView.mas_bottom);
        } else {
            make.top.mas_equalTo(self);
        }
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        if (bottomView) {
            make.bottom.mas_equalTo(bottomView.mas_top);
        } else {
            make.bottom.mas_equalTo(self);
        }
    }];
}
    
- (void)reloadViewByNewListModels:(NSArray *)listModels
{
    self.showListArray = [NSMutableArray arrayWithArray:listModels];
    [self.facCollectionView setCellModelArray:self.showListArray];
    [self.facCollectionView reloadListView];
    [self updateConfirmButtonTitle];
    [self updateSelectedView];
}

- (void)updateSelectedView
{
    if (self.viewLayout.isShowBottomSelectedView) {
        
        CGFloat defaultHeight = 46;
        CGFloat bottomSpace = 0;
        if (self.settingModel.selectedModelArray.count) {
            [self.bottomSelectedView setHidden:NO];
        } else {
            [self.bottomSelectedView setHidden:YES];
            bottomSpace = defaultHeight;
        }

        [self.bottomSelectedView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(bottomSpace);
            make.left.offset(0);
            make.right.offset(0);
            make.height.mas_equalTo(defaultHeight);
        }];
        
        [self.bottomSelectedView reloadView:self.settingModel.selectedModelArray isUp:YES];
    }
}

#pragma mark - button click

- (void)confirmAction
{
    [self saveSelectedModel];
}

- (void)lookingAllAction
{
    [self.settingModel.selectedModelArray removeAllObjects];
    self.showListArray = [LBCategorySettingModel getListModelBySettingModel:self.settingModel currentPage:self.viewLayout.pageType];
    [self reloadViewByNewListModels:self.showListArray];
    if (self.choseBlock) {
        self.viewLayout.isLookingAll = YES;
        self.choseBlock(self.viewLayout,nil);
    }
}

#pragma mark - click

- (void)dealWithDelActionFromDelIndexPath:(NSIndexPath *)indexPath withDelModel:(LBCategoryModel *)model
{
    if (!model) {
        return;
    }
    
    if (self.settingModel.isEdiotr) {
        
        NSIndexPath *moveToIndexPath = [self indexPathForDelMoveToByDelModel:model];
        /*
         LBCategoryMainViewDelTypeInTwoLevel,//在二级
         LBCategoryMainViewDelTypeInThreeLevel,//在三级
         LBCategoryMainViewDelTypeNoIn,//都不在
         */
        if (LBCategoryMainViewDelTypeInTwoLevel == self.moveToType) {
            NSMutableArray *moveToArray = [NSMutableArray arrayWithArray:self.showListArray[moveToIndexPath.section]];
            [moveToArray insertObject:model atIndex:0];
            [self.showListArray replaceObjectAtIndex:moveToIndexPath.section withObject:moveToArray];
            [self.settingModel onlyRemoveCategoryModel:model currentPage:self.viewLayout.pageType];
            [self delModelFromOriginalListByIndexPath:indexPath withDoModel:model];
            [self moveFromBegionIndexPath:indexPath toIndexPath:moveToIndexPath];
        } else if (LBCategoryMainViewDelTypeInThreeLevel == self.moveToType) {
            [self.settingModel onlyRemoveCategoryModel:model currentPage:self.viewLayout.pageType];
            [self delModelFromOriginalListByIndexPath:indexPath withDoModel:model];
            [self.facCollectionView.collectionView performBatchUpdates:^{
                [self.facCollectionView.collectionView deleteItemsAtIndexPaths:@[indexPath]];
            } completion:^(BOOL finished) {
                [self updateTopShowSelectedListView];
            }];
        } else {
            [self.settingModel onlyRemoveCategoryModel:model currentPage:self.viewLayout.pageType];
            [self delModelFromOriginalListByIndexPath:indexPath withDoModel:model];
            NSArray *newArray = [NSArray arrayWithObject:model];
            [self.showListArray insertObject:newArray atIndex:1];
            [self updateTopShowSelectedListView];
        }
    } else {
        LBCategoryModel *model = nil;
        if (indexPath.row < self.settingModel.selectedModelArray.count) {
            model = self.settingModel.selectedModelArray[indexPath.row];
        }
        if (self.choseBlock  && model) {
            self.viewLayout.bookingSelectedModel = model;
            self.choseBlock(self.viewLayout,@[model]);
        }
    }
    
}

- (void)doAddModelByIndexPath:(NSIndexPath *)indexPath
                 withAddModel:(LBCategoryModel *)model
{
    if (!model) {
        return;
    }
    
    NSLog(@"%@",@(indexPath.row));
    
    self.settingModel.isEdiotr = YES;
    
    NSIndexPath *addIndexPath = [self indexPathForAddModelMoveTo];

    [self.settingModel onlyAddCategoryModel:model currentPage:self.viewLayout.pageType];
    //删除新加数据在原列表的位置
    [self delModelFromOriginalListByIndexPath:indexPath withDoModel:model];
    //新增数据
    NSMutableArray *showSelectedArray = [NSMutableArray arrayWithArray:[self.showListArray firstObject]];
    [showSelectedArray addObject:model];
    [self.showListArray replaceObjectAtIndex:0 withObject:showSelectedArray];
    [self moveFromBegionIndexPath:indexPath toIndexPath:addIndexPath];
}

- (void)delModelFromOriginalListByIndexPath:(NSIndexPath *)indexPath
                                withDoModel:(LBCategoryModel *)model
{
    //删除原数组种被消除的数据
    __block NSMutableArray *removeArray = [NSMutableArray array];
    [self.showListArray enumerateObjectsUsingBlock:^(NSArray<LBCategoryModel *> * _Nonnull firstLevelArray, NSUInteger firstLevelidx, BOOL * _Nonnull firstLevelstop) {
        if (firstLevelidx == indexPath.section) {
            [firstLevelArray enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                obj.isEdiotr = YES;
                if (indexPath.row != idx) {
                    [removeArray addObject:obj];
                }
            }];
            *firstLevelstop = YES;
        }
    }];
    [self.showListArray replaceObjectAtIndex:indexPath.section withObject:removeArray];
}

- (NSIndexPath *)indexPathForAddModelMoveTo
{
    //增加插入到最末尾
    NSInteger selectedCount = [[self.showListArray firstObject]count];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:selectedCount inSection:0];
    return indexPath;
}

- (NSIndexPath *)indexPathForDelMoveToByDelModel:(LBCategoryModel *)delModel
{
    //删除插入到最前端
    __block NSIndexPath *indexPath = nil;
    
    self.moveToType = LBCategoryMainViewDelTypeNoIn;
    
    __weak __typeof(&*self)weakSelf = self;
    [self.showListArray enumerateObjectsUsingBlock:^(NSArray *showArray, NSUInteger showidx, BOOL * _Nonnull showstop) {
        if (showidx != 0) {
            [showArray enumerateObjectsUsingBlock:^(LBCategoryModel *model, NSUInteger twoidx, BOOL * _Nonnull twostop) {
                if ([model.parCode isEqualToString:delModel.parCode]) {
                    //同一个父类 同为二级分类
                    indexPath = [NSIndexPath indexPathForRow:0 inSection:showidx];
                    weakSelf.moveToType = LBCategoryMainViewDelTypeInTwoLevel;
                    *twostop = YES;
                    *showstop = YES;
                } else {
                    [model.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull threeObj, NSUInteger threeidx, BOOL * _Nonnull threestop) {
                        if ([threeObj.code isEqualToString:delModel.code]) {
                            //在三级分类
                            weakSelf.moveToType = LBCategoryMainViewDelTypeInThreeLevel;
                            *showstop = YES;
                        }
                    }];
                }
                
            }];
        }
    }];
    
    return indexPath;
}

- (void)moveFromBegionIndexPath:(NSIndexPath *)fromIndexPath
                        toIndexPath:(NSIndexPath *)toIndexPath
{
    NSLog(@"from:%@ : %@",@(fromIndexPath.section),@(fromIndexPath.row));
    NSLog(@"to:%@ : %@",@(toIndexPath.section),@(toIndexPath.row));
    
    [self.facCollectionView.collectionView performBatchUpdates:^{
        [self.facCollectionView.collectionView moveItemAtIndexPath:fromIndexPath toIndexPath:toIndexPath];
    } completion:^(BOOL finished) {
        [self updateTopShowSelectedListView];
    }];
}

- (void)updateTopShowSelectedListView
{
    __weak __typeof(&*self)weakSelf = self;
    //    self.showListArray = [LBCategorySettingModel getListModelBySettingModel:self.settingModel currentPage:self.viewLayout.pageType];
    NSMutableArray *listArray = [NSMutableArray array];
    [self.showListArray enumerateObjectsUsingBlock:^(NSArray *oneArray, NSUInteger oneidx, BOOL * _Nonnull onestop) {
        if (0 == oneidx) {
            [oneArray enumerateObjectsUsingBlock:^(LBCategoryModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.isChosedCell = YES;
                obj.isEdiotr = weakSelf.settingModel.isEdiotr;
                obj.isSelected = YES;
            }];
            [listArray addObject:oneArray];
        } else {
            [oneArray enumerateObjectsUsingBlock:^(LBCategoryModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.isChosedCell = NO;
                obj.isEdiotr = NO;
                obj.isSelected = NO;
            }];
            if (oneArray.count) {
                //去除空数组
                [listArray addObject:oneArray];
            }
        }
    }];
    [self reloadViewByNewListModels:listArray];
}

//- (void)updateListViewModelAndRefreshView:(BOOL)isRefreshView
//{
//    __weak __typeof(&*self)weakSelf = self;
//    [self.showListArray enumerateObjectsUsingBlock:^(NSArray<LBCategoryModel *> * _Nonnull sectionArray, NSUInteger sectionidx, BOOL * _Nonnull sectionstop) {
//        [sectionArray enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (0 == sectionidx) {
//                obj.isEdiotr = self.settingModel.isEdiotr;
//                obj.isChosedCell = YES;
//                obj.isSelected = YES;
//            } else {
//                obj.isEdiotr = NO;
//                obj.isChosedCell = NO;
//                if ([weakSelf.settingModel containsCategoryCode:obj.code fromSelectedArray:weakSelf.settingModel.currentSelectedModelArray]) {
//                    obj.isSelected = YES;
//                } else {
//                    obj.isSelected = NO;
//                }
//            }
////            if (isRefreshView) {
////                LBCategoryCell *cell = (LBCategoryCell *)[self.facCollectionView.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:sectionidx]];
////                [cell fac_updateUIViewByModel:obj];
////            }
//        }];
//    }];
//}

- (void)dealWithAddActionFromIndexPath:(NSIndexPath *)indexPath
                          withAddModel:(LBCategoryModel *)model
{
    __weak __typeof(&*self)weakSelf = self;
    if ([self.settingModel isShowNextLevel:self.viewLayout.pageType]
        && model.chirdrenNode.count) {
        //三级展示 且 有三级数据
        [weakSelf pushToThreeLevelShowPageModel:model];
    } else {
        [self doAddModelByIndexPath:indexPath withAddModel:model];
    }
}

- (void)pushToThreeLevelShowPageModel:(LBCategoryModel *)model
{
    __weak __typeof(&*self)weakSelf = self;
    LBCYThreeLevelShowViewController *threeViewController = [[LBCYThreeLevelShowViewController alloc]init];
    [weakSelf.settingModel setCurrentShowArrayByData:[LBCategorySettingModel getCopyByOriginalData:model.chirdrenNode]];
    [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeHomePage toPage:LBCategorySettingPageTypeThreeLevel];
    [threeViewController updateBySettingModel:self.settingModel choseBlock:^(NSMutableArray *selectedArry){
        
        weakSelf.settingModel.isEdiotr = YES;
        
        [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeThreeLevel toPage:LBCategorySettingPageTypeHomePage];
//        if (weakSelf.settingModel.isSingleSelected) {
//            [weakSelf confirmAction];
//        }
//        weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:self.viewLayout.pageType];
//        [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
    }];
    
    UINavigationController *currentNavViewController = [UIApplication getCurrentViewController].navigationController;
    
    if (!currentNavViewController) {
        currentNavViewController = [UIApplication sharedApplication].keyWindow.rootViewController ;
    }
    
    [currentNavViewController pushViewController:threeViewController animated:YES];

}

#pragma mark - model change

- (void)modelSelectedChange
{
    //更新底部选中状态
    [self updateSelectedView];
}

- (void)allModelSelectedChange
{
    //更新三级页面选中
    [self updateConfirmButtonTitle];
}

- (NSInteger)getRealCount
{
    __block NSInteger count = 0;
    
    if (LBCategorySettingPageTypeThreeLevel == self.viewLayout.pageType) {
        [self.showListArray enumerateObjectsUsingBlock:^(NSArray  *array, NSUInteger allidx, BOOL * _Nonnull allstop) {
            [array enumerateObjectsUsingBlock:^(LBCategoryModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.isSelected) {
                    count ++;
                }
            }];
        }];
    }

    return count;
}

#pragma mark - model dealWith

- (NSMutableArray *)getSelectedModelArrayBySelectedCodeArray:(NSArray <NSString *>*)codeArray
                                        inOriginalModelArray:(NSArray <LBCategoryModel *>*)totalModelArray
{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    if (!codeArray.count) {
        return resultArray;
    }
    
    [totalModelArray enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull firstLevelObj, NSUInteger firstLevelidx, BOOL * _Nonnull firstLevestop) {
        [firstLevelObj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull secondLevelobj, NSUInteger secondLevelidx, BOOL * _Nonnull secondLevelstop) {
            
            if ([codeArray containsObject:secondLevelobj.code]) {
                [resultArray addObject:secondLevelobj];
            } else {
                [secondLevelobj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull thirdLevelobj, NSUInteger thirdLevelidx, BOOL * _Nonnull thirdLevelstop) {
                    if ([codeArray containsObject:thirdLevelobj.code]) {
                        [resultArray addObject:thirdLevelobj];
                    } else {
                        //四级
                        [thirdLevelobj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull fourthObj, NSUInteger fourthidx, BOOL * _Nonnull fourthstop) {
                            if ([codeArray containsObject:fourthObj.code]) {
                                [resultArray addObject:fourthObj];
                            }
                        }];
                    }
                }];
            }
            
        }];
    }];
    
    return resultArray;
}

- (NSMutableArray *)getUnSelectedModelArrayBySelectedCodeArray:(NSArray <NSString *>*)codeArray
                                          inOriginalModelArray:(NSArray <LBCategoryModel *>*)totalModelArray
{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    [totalModelArray enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull firstLevelObj, NSUInteger firstLevelidx, BOOL * _Nonnull firstLevestop) {
        NSMutableArray *secondLevelArray = [NSMutableArray array];
        [firstLevelObj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull secondLevelobj, NSUInteger secondLevelidx, BOOL * _Nonnull secondLevelstop) {
            
            if (![codeArray containsObject:secondLevelobj.code]) {
                
                NSMutableArray *thirdlevelArray = [NSMutableArray array];
                
                [secondLevelobj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull thirdLevelobj, NSUInteger thirdLevelidx, BOOL * _Nonnull thirdLevelstop) {
                    if (![codeArray containsObject:thirdLevelobj.code]) {
                        [thirdlevelArray addObject:thirdLevelobj];
                    }
                }];
                
                secondLevelobj.chirdrenNode = [NSArray arrayWithArray:thirdlevelArray];
                
                [secondLevelArray addObject:secondLevelobj];
            }
        }];
        
        if (secondLevelArray.count) {
            [resultArray addObject:secondLevelArray];
        }
    }];
    return resultArray;
}

- (NSIndexPath *)getUnSelectedAddIndexPathByCategoryMode:(LBCategoryModel *)categoryModel
{
    __block NSIndexPath *indexPath = nil;
    
    [self.showListArray enumerateObjectsUsingBlock:^(NSArray<LBCategoryModel *> * _Nonnull firstArray, NSUInteger firstLevelidx, BOOL * _Nonnull firstLevelstop) {
        if (firstLevelidx != 0) {
            [firstArray enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull secondLevelObj, NSUInteger secondLevelidx, BOOL * _Nonnull secondLevelstop) {
                if ([categoryModel.parCode isEqualToString:secondLevelObj.parCode]) {
                    //同一个父类
                    indexPath = [NSIndexPath indexPathForRow:0 inSection:firstLevelidx];
                    *secondLevelstop = YES;
                } else {
                    [secondLevelObj.chirdrenNode enumerateObjectsUsingBlock:^(LBCategoryModel * _Nonnull thirdLevelobj, NSUInteger thirdLevelidx, BOOL * _Nonnull thirdLevelstop) {
                        if ([categoryModel.parCode isEqualToString:thirdLevelobj.parCode]) {
                            //处于三级 row 设置为 > 0 说明三级分类 section 设为 0
                            indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
                            *secondLevelstop = YES;
                        }
                    }];
                }
            }];
        }
    }];
    
    return indexPath;
}

- (NSIndexPath *)getSelectedAddIndexPathBySelectedModelArray:(NSArray *)selectedModelArray
{
    __block NSIndexPath *indexPath = nil;
    
    NSInteger maxIndex = (selectedModelArray.count - 1);
    
    if (maxIndex < 0) {
        maxIndex = 0;
    }
    
    indexPath = [NSIndexPath indexPathForRow:maxIndex inSection:0];
    
    return indexPath;
}

- (NSInteger)indexForLastEmptyArray
{
    __block NSInteger emptyIndex = 0;
    [self.showListArray enumerateObjectsUsingBlock:^(NSArray<LBCategoryModel *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (0 != idx) {
            if (!obj.count) {
                emptyIndex = idx;
                *stop = YES;
            }
        }
    }];
    return emptyIndex;
}

- (void)saveSelectedModel
{
    NSMutableArray *saveModelArray;
    
    if (LBCategorySettingPageTypeThreeLevel == self.viewLayout.pageType) {
        saveModelArray = self.settingModel.threePageSelectedModelArray;
    } else if (LBCategorySettingPageTypeSearchLevel == self.viewLayout.pageType) {
        saveModelArray = self.settingModel.searchPageSelectedModelArray;
    } else {
        saveModelArray = self.settingModel.selectedModelArray;
    }
    if (saveModelArray.count) {
        if (self.choseBlock) {
            self.choseBlock(self.viewLayout,saveModelArray);
        }
    } else {
        if ([self.settingModel isBookingCodeType]) {
            [LBToastView showByMessage:@"我的订阅不能为空"];
        } else {
            [LBToastView showByMessage:@"至少选择一个分类"];
        }
    }
}

- (void)saveBookingSelected
{
    __weak __typeof(&*self)weakSelf = self;
    
    if (LBCategoryBizCodeTypeBookingRequirement == self.settingModel.codeType ||
        LBCategoryBizCodeTypeBookingResource == self.settingModel.codeType) {
        NSMutableArray *bizCodeArray = [NSMutableArray array];
        NSMutableArray *bizTypeArray = [NSMutableArray array];
        
        [weakSelf.settingModel.selectedModelArray enumerateObjectsUsingBlock:^(LBCategoryModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.code) {
                [bizCodeArray addObject:obj.code];
                [bizTypeArray addObject:@(weakSelf.settingModel.codeType)];
            }
        }];
        
        [LBLoadingView showInView:self];
        [LBCategoryManager saveBookingByBizCode:bizCodeArray BizType:bizTypeArray Success:^{
            [LBLoadingView dismiss];
            if (weakSelf.choseBlock) {
                weakSelf.choseBlock(weakSelf.viewLayout,weakSelf.settingModel.selectedModelArray);
            }
        } fail:^(NSString *errMsg) {
            [LBLoadingView dismiss];
            [LBAlert say:errMsg];
        }];
    }
}

- (void)updateConfirmButtonTitle
{
    NSInteger count = [self getRealCount];
    __weak __typeof(&*self)weakSelf = self;
    NSString *str = @"确定";
    if (!count) {
        [weakSelf.confirmButton setAttributedTitle:[[NSMutableAttributedString alloc]initWithString:str] forState:UIControlStateNormal];
        return ;
    }
    NSString *fitlerStr = [NSString stringWithFormat:@"(已选%@个)",@(count)];
    str = [NSString stringWithFormat:@"确定 %@",fitlerStr];
    NSRange range = [str rangeOfString:fitlerStr];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:str];
    [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:range];
    [weakSelf.confirmButton setAttributedTitle:attr forState:UIControlStateNormal];
}

#pragma mark - setter

#pragma mark - getter

- (LBFacListView *)facCollectionView
{
    if (!_facCollectionView) {
        __weak __typeof(&*self)weakSelf = self;
        _facCollectionView = [[LBFacListView alloc]initCollectionViewWithFlowLayout:[[LBFacCategoryFlowLayout alloc]init] frame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)) cellName:@"LBCategoryCell" maxItemsOneLine:4 click:^(NSIndexPath *indexPath) {
            LBCategoryModel *model = weakSelf.showListArray[indexPath.section][indexPath.row];
            if (weakSelf.viewLayout.isShowTopSelectedView) {
                
                NSLog(@"%@",@(indexPath.row));
                
                if (0 == indexPath.section) {
                    //删除
                    [weakSelf dealWithDelActionFromDelIndexPath:indexPath withDelModel:model];
                } else {
                    //添加
                    [weakSelf dealWithAddActionFromIndexPath:indexPath withAddModel:model];
                }
            } else {
                //有三级展示三级
                if ([weakSelf.settingModel isShowNextLevel:weakSelf.viewLayout.pageType]
                    && model.chirdrenNode.count) {
                    //三级展示 且 有三级数据
                    [weakSelf pushToThreeLevelShowPageModel:model];
                } else {
                    if (weakSelf.settingModel.isSingleSelected) {
                        if (model.isAllAll) {
                            //点击全部分类
                            [weakSelf lookingAllAction];
                            return ;
                        }
                        //所有单选即可返回
                        weakSelf.viewLayout.isLookingAll = NO;
                        model.isSelected = YES;
                        [weakSelf.settingModel addCategoryModel:model currentPage:weakSelf.viewLayout.pageType];
                        if (weakSelf.settingModel.confirmBlock) {
                            weakSelf.settingModel.confirmBlock(weakSelf.viewLayout,@[model]);
                        }
                        return ;
                    }
                    
                    //没三级选中
                    //二级时候选中直接添加到选中列表
                    if (model.isSelected) {
                        //标记选中取消的分类
                        [weakSelf.settingModel removeCategoryModel:model currentPage:self.viewLayout.pageType];
                        model.isSelected = NO;
                    } else {
                        [weakSelf.settingModel addCategoryModel:model currentPage:weakSelf.viewLayout.pageType];
                        model.isSelected = YES;
                    }
        
//                    [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
//
//                    [weakSelf updateConfirmButtonTitle];
                }
            }
            
        } otherClick:nil];
        _facCollectionView.isOneSection = NO;
        [_facCollectionView registerHeaderViewClass:[LBCategoryTopHeaderReusableView class] HeaderModelBlock:^id(NSInteger section) {
            if (weakSelf.viewLayout.isHideSectionView) {
                return nil;
            }
            LBCategoryModel *model = [weakSelf.showListArray[section]lastObject];
            
            return [LBCategoryHeaderViewModel headerModelBySection:section settingModel:weakSelf.settingModel viewLayout:weakSelf.viewLayout selectedModel:model];
            
        }HeaderViewClick:^(NSInteger index) {
            if (0 == index) {
                weakSelf.settingModel.isEdiotr = YES;
                [weakSelf updateTopShowSelectedListView];
            } else {
                [weakSelf saveBookingSelected];
            }
        }];
//        [_facCollectionView customCollectionCellWithSize:^CGSize(NSIndexPath *indexPath) {
//            
//            if (!weakSelf.viewLayout.isShowTopSelectedView) {
//                return CGSizeZero;
//            }
//            
//            LBCategoryModel *model = weakSelf.showListArray[indexPath.section][indexPath.row];
//            if (0 == indexPath.section && model) {
//                return [LBCategorySelectedChildView sizeForViewByModel:model];
//            } else {
//                return CGSizeZero;
//            }
//        }];
    }
    return _facCollectionView;
}

- (LBCategoryMainViewLayout *)viewLayout
{
    if (!_viewLayout) {
        _viewLayout = [[LBCategoryMainViewLayout alloc]init];
    }

    return _viewLayout;
}

- (LBNewCategorySearchView *)searchView
{
    if (!_searchView) {
        __weak __typeof(&*self)weakSelf = self;
        _searchView = [[LBNewCategorySearchView alloc]initWithFrame:CGRectZero complete:^(NSString *content) {
            
            LBCategorySearchViewController *searchVC = [[LBCategorySearchViewController alloc]init];
                        
            if (LBCategorySettingPageTypeHomePage == weakSelf.viewLayout.pageType) {
                //全部搜索
                [weakSelf.settingModel setCurrentShowArrayByData:[weakSelf.settingModel getSearchAllModel]];
                [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeHomePage toPage:LBCategorySettingPageTypeSearchLevel];
                [searchVC updateBySettingModel:weakSelf.settingModel choseBlock:^(NSMutableArray *selectedArry) {
                    
                    weakSelf.settingModel.isEdiotr = YES;
                    
                    [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeSearchLevel toPage:LBCategorySettingPageTypeHomePage];
                    
//                    if (weakSelf.settingModel.isSingleSelected) {
//                        [weakSelf saveSelectedModel];
//                    }
                    
                    
                    
//                    weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:self.viewLayout.pageType];
//
//                    [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
                }];
            } else {
                //三级分类搜索
                [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeThreeLevel toPage:LBCategorySettingPageTypeSearchLevel];
                [searchVC updateBySettingModel:weakSelf.settingModel choseBlock:^(NSArray *selectedModeArray) {
                    weakSelf.settingModel.isEdiotr = YES;
                    [weakSelf.settingModel dealWithSelectedArrayFromPage:LBCategorySettingPageTypeSearchLevel toPage:LBCategorySettingPageTypeThreeLevel];
                    
//                    if (weakSelf.settingModel.isSingleSelected) {
//                        [weakSelf saveSelectedModel];
//                    }
//
//                    weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:self.viewLayout.pageType];
//                    [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
                }];
            }
            
            UINavigationController *currentNavViewController = [UIApplication getCurrentViewController].navigationController;
            
            if (!currentNavViewController) {
                currentNavViewController = [UIApplication sharedApplication].keyWindow.rootViewController ;
            }
            
            [currentNavViewController pushViewController:searchVC animated:YES];
        }];
    }
    return _searchView;
}

- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:[UIColor blue] forState:UIControlStateNormal];
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor lightBlue] forState:UIControlStateHighlighted];
        [_confirmButton addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

//- (UIButton *)lookAllButton
//{
//    if (!_lookAllButton) {
//        _lookAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_lookAllButton setTitle:@"查看全部分类" forState:UIControlStateNormal];
//        _lookAllButton.titleLabel.font = [UIFont systemFontOfSize:14];
//        [_lookAllButton setTitleColor:[UIColor blue] forState:UIControlStateNormal];
//        [_lookAllButton setTitleColor:[UIColor lightBlue] forState:UIControlStateHighlighted];
//        [_lookAllButton setImage:[UIImage imageNamed:@"Category.bundle/lb_category_down"] forState:UIControlStateNormal];
//        [_lookAllButton layoutIfNeeded];
//        [_lookAllButton addTarget:self action:@selector(lookingAllAction) forControlEvents:UIControlEventTouchUpInside];
//        _lookAllButton.backgroundColor = [UIColor whiteColor];
//    }
//    return _lookAllButton;
//}

- (LBCategorySelectedView *)bottomSelectedView
{
    if (!_bottomSelectedView) {
        __weak __typeof(&*self)weakSelf = self;
        _bottomSelectedView = [[LBCategorySelectedView alloc]initWithFrame:CGRectZero isSingleSelected:NO complete:^(LBCategorySelectedViewBlockType blockType){
            
            if (LBCategorySelectedViewBlockTypeLooking == blockType) {
                LBCategoryPopuViewType type = LBCategoryPopuViewTypeNextStep;
                
                [LBCategoryPopuView showByType:type listModels:weakSelf.settingModel.selectedModelArray model:weakSelf.settingModel complete:^(LBCategoryPopuViewBlockType type){
                    if (LBCategoryPopuViewBlockTypeComplete == type) {
                        [weakSelf saveSelectedModel];
                    } else {
                        weakSelf.showListArray = [LBCategorySettingModel getListModelBySettingModel:weakSelf.settingModel currentPage:weakSelf.viewLayout.pageType];
                        if (!weakSelf.settingModel.selectedModelArray.count) {
                            //删除为空
                            [LBCategoryPopuView dimiss];
                            [weakSelf updateSelectedView];
                        }
                        [weakSelf reloadViewByNewListModels:weakSelf.showListArray];
                    }
                }];
            } else {
                [weakSelf saveSelectedModel];
            }
        }];
    };
    return _bottomSelectedView;
}

@end


@implementation LBCategoryMainViewLayout

- (LBCategorySettingPageType)pageType
{
    if (!_pageType) {
        _pageType = LBCategorySettingPageTypeHomePage;
    }
    return _pageType;
}

@end
